#include "List.h"

ListNode* ListCreate()
{
	ListNode* head = (ListNode*)malloc(sizeof(ListNode));
	if (head == NULL)
	{
		perror("malloc");
		return NULL;
	}
	head->prev = head;
	head->next = head;

	return head;
}

void ListDestory(ListNode* plist)
{
	assert(plist);

	ListNode* cur = plist->next;
	while (cur != plist)
	{
		ListNode* next = cur->next;
		free(cur);
		cur = next;
	}
	free(plist);
}

void ListPrint(ListNode* plist)
{
	assert(plist);

	ListNode* cur = plist->next;
	printf("head<==>");
	while (cur != plist)
	{
		printf("%d<==>", cur->data);
		cur = cur->next;
	}
	printf("head\n");
}

void ListPushBack(ListNode* plist, ListDataType x)
{
	assert(plist);

	ListNode* newnode = ListCreate();
	newnode->data = x;

	ListNode* tail = plist->prev;
	tail->next = newnode;
	newnode->prev = tail;
	newnode->next = plist;
	plist->prev = newnode;
}

void ListPopBack(ListNode* plist)
{
	assert(plist && plist->next);

	ListNode* tail = plist->prev;
	ListNode* prev = tail->prev;
	prev->next = plist;
	plist->prev = prev;
	free(tail);
}

void ListPushFront(ListNode* plist, ListDataType x)
{
	assert(plist);

	ListNode* newnode = ListCreate();
	newnode->data = x;

	ListNode* cur = plist->next;
	plist->next = newnode;
	newnode->prev = plist;
	newnode->next = cur;
	cur->prev = newnode;
}

void ListPopFront(ListNode* plist)
{
	assert(plist && plist->next);

	ListNode* cur = plist->next;
	ListNode* next = cur->next;
	plist->next = next;
	next->prev = plist;
	free(cur);
}

ListNode* ListFind(ListNode* plist, ListDataType x)
{
	assert(plist);

	ListNode* cur = plist->next;
	while (cur != plist)
	{
		if (cur->data == x) return cur;
		cur = cur->next;
	}
	return NULL;
}

void ListInsert(ListNode* pos, ListDataType x)
{
	assert(pos);

	ListNode* newnode = ListCreate();
	newnode->data = x;

	ListNode* prev = pos->prev;
	prev->next = newnode;
	newnode->prev = prev;
	newnode->next = pos;
	pos->prev = newnode;
}

void ListErase(ListNode* pos)
{
	assert(pos);

	ListNode* prev = pos->prev;
	ListNode* next = pos->next;
	prev->next = next;
	next->prev = prev;
	free(pos);
}